-- UISkyWhirlpoolInfo
-- Create By huanghr Feb/22/2015
-- 时空裂痕页面

-- UISkyWhirlpoolInfo继承自Layer
UISkyWhirlpoolInfo = class("UISkyWhirlpoolInfo", function()
    return cc.Layer:create();
end);

function UISkyWhirlpoolInfo.create(info)
    return UISkyWhirlpoolInfo.new(info);
end

-- 内部函数声明
local offsetY = 0;
local fixWidth = 0;

local MAX_GRID_ROW    = 1;
local MIN_GRID_COLUMN = 4;

-- 构造函数
function UISkyWhirlpoolInfo:ctor(info)
    -- 初始化
    self:setName("UISkyWhirlpoolInfo");

    -- 复用飞艇信息页面
    local node = cc.CSLoader:createNode("layout/sky_city/IslandInfo.csb");
    self:addChild(node);
    self.node = node;

    self.info = info;

    -- 阵营
    self.camp = info.camp;

    local bonusNode = findChildByName(self.node, "BT2/desc_node/bonus_node");
    self.scrollView = findChildByName(bonusNode, "bonus_panel");

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 标题和描述在中间浮现
    self:comformCenterEffect();

    -- 播放准心特效
    playReticleEffect(self.node);

    -- 适配
    self:resize();
end

-- 分析浮岛信息
function UISkyWhirlpoolInfo:initData()
    -- 标题
    local color = CampM.query(self.camp, "whirlpool_color");

    local title = string.format(getLocStr("whirlpool_title"), color);

    local level = self.info["explore_level"];

    local totalFight, ability = self:getAbilityInfo();

    local data = {};
    data = {
        ["title"]       = title,
        ["ability"]     = ability,
        ["totalFight"]  = totalFight;
        ["level"] = level;
    };

    return data;
end

-- 编辑战力信息
function UISkyWhirlpoolInfo:getAbilityInfo()
    -- 标题
    local combatIds = self.info["whirlpool_combat"];

    local abilityInfo = {};

    local fireList = {};
    local armorList = {};
    local luckList = {};
    local speedList = {};

    local totalFight = 0;

    printTable(combatIds, "cambat_ids");

    for k, v in pairs(combatIds) do
        local combatInfo = SkyWhirlpoolM.calcWhirlpoolAttrib(v, self.info["explore_level"]);

        table.insert(fireList, combatInfo.fire);

        table.insert(armorList, combatInfo.armor);


        table.insert(luckList, combatInfo.luck);


        table.insert(speedList, combatInfo.speed);

        totalFight = combatInfo.fight_ability + totalFight;
    end

    -- 最小值
    local function minNum(list)
        local min = nil;
        for _, v in pairs(list) do
            min = min or v;

            if min > v then
                min = v;
            end
        end

        return min;
    end

    -- 最大值
    local function maxNum(list)
        local max = nil;
        for _, v in pairs(list) do
            max = max or v;

            if max < v then
                max = v;
            end
        end

        return max;
    end

    printTable(fireList, "fire_list");


    abilityInfo.minFire = minNum(fireList);
    abilityInfo.maxFire = maxNum(fireList);

    abilityInfo.minArmor = minNum(armorList);
    abilityInfo.maxArmor = maxNum(armorList);

    abilityInfo.minLuck = minNum(luckList);
    abilityInfo.maxLuck = maxNum(luckList);

    abilityInfo.minSpeed = minNum(speedList);
    abilityInfo.maxSpeed = maxNum(speedList);


    return totalFight, abilityInfo;
end

-- 适配
function UISkyWhirlpoolInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");
    AlignM.fitToScreen(node, "bg2");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- 顶部区域至于顶部并缩放至合适大小
    local topNode = findChildByName(node, "Top");
    topNode:setVisible(true);

    AlignM.alignToTopCenter(node, "Top");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
    AlignM.alignToBottomCenter(node, "BT2");
end

-- 重绘界面
function UISkyWhirlpoolInfo:redraw()
    -- 构造分析浮岛详细信息
    local data = self:initData();

    -- 显示标题
    local titleLabel = findChildByName(self.node, "Top/title/text");

    titleLabel:setString(data.title);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 绘制图标
    local icon = findChildByName(self.node, "CT/tower_node");

    -- 修正回正中
    icon:setPositionX(0);

    local WhirlpoolNode = self:createWhirlpoolIsland(self.camp);
    WhirlpoolNode:setPositionY(-65);
    WhirlpoolNode:setScale(0.9);

    WhirlpoolNode.id = self.camp;
    WhirlpoolNode:setName("whirlpool");
    icon:addChild(WhirlpoolNode);

    icon:setOpacity(0);

    local delay     = cc.DelayTime:create(0.2);
    local fadeIn = cc.FadeIn:create(0.4);
    icon:runAction(cc.Sequence:create(delay, fadeIn));

    -- 四维信息
    local ability = data.ability;

    local abilityStr = "%d-%d";

    local detailNode = findChildByName(self.node, "CT/detail_node");
    -- 火力
    local attribLabel = findChildByName(detailNode, "fire_node/attrib");
    local valueLabel = findChildByName(detailNode, "fire_node/value");
    self:resetLabelPos(valueLabel);

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_fire"));
    valueLabel:setString(string.format(abilityStr, ability.minFire, ability.maxFire));

    -- 装甲
    attribLabel = findChildByName(detailNode, "armor_node/attrib");
    valueLabel = findChildByName(detailNode, "armor_node/value");
    self:resetLabelPos(valueLabel);

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_armor"));
    valueLabel:setString(string.format(abilityStr, ability.minArmor, ability.maxArmor));

    -- 机动
    attribLabel = findChildByName(detailNode, "speed_node/attrib");
    valueLabel = findChildByName(detailNode, "speed_node/value");
    self:resetLabelPos(valueLabel);

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_speed"));
    valueLabel:setString(string.format(abilityStr, ability.minSpeed, ability.maxSpeed));

    -- 幸运
    attribLabel = findChildByName(detailNode, "luck_node/attrib");
    valueLabel = findChildByName(detailNode, "luck_node/value");
    self:resetLabelPos(valueLabel);

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("airship_luck"));
    valueLabel:setString(string.format(abilityStr, ability.minLuck, ability.maxLuck));

    -- 总战力
    attribLabel = findChildByName(detailNode, "ability_node/attrib");
    valueLabel = findChildByName(detailNode, "ability_node/value");

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("total_fight_ability"));

    -- 逗号分段战力
    valueLabel:setString(thousandNum(data.totalFight));

    -- 战斗次数
    attribLabel = findChildByName(detailNode, "camp_node/attrib");
    valueLabel = findChildByName(detailNode, "camp_node/value");

    self:setSystemTextStyle(attribLabel);
    self:setSystemTextStyle(valueLabel);

    attribLabel:setString(getLocStr("sequence_combat"));

    valueLabel:setString(string.format(getLocStr("fight_session"), self.info["combat_num"]));

    -- 信息出现特效
    playAirShipInfoEffect(detailNode);

    -- 重绘描述
    self:redrawDesc();

    -- 绘制奖励
    self:redrawBonus();

    -- 隐藏按钮
    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);
end

-- 清空所有的奖励格
function UISkyWhirlpoolInfo:clearAllGrid()
    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();
end

-- 绘制奖励
function UISkyWhirlpoolInfo:redrawBonus()
    local bonusNode = findChildByName(self.node, "BT2/desc_node/bonus_node");
    bonusNode:setVisible(true);
    local panel = findChildByName(bonusNode, "bonus_panel");

    -- 收集信息
    local bonus = FormulaM.invoke("CALC_SKY_EVENT_BONUS",  self.info.id, self.info.explore_level, self.camp);

    local goodsList = {};
    if type(bonus[1]) == "number" then
        goodsList = {bonus};
    else
        goodsList = bonus;
    end

    -- 显示奖励信息
    local totalGoodsCount = #goodsList;

    if totalGoodsCount < 1 then
        return;
    end

    local totalGridCount = 4
    if totalGoodsCount > 4 then
        totalGridCount = totalGoodsCount;
    end
    -- 初始化格子
    self:initGrids(totalGridCount);

    for i = 1, totalGridCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local buyImg        = grid:getChildByName("buy");
        local starNode      = grid:getChildByName("stars");
        local numLabel      = grid:getChildByName("num_label");
        local countLabel    = grid:getChildByName("num");
        local iconImg       = grid:getChildByName("icon");

        countLabel:setVisible(true);
        numLabel:setVisible(false);
        buyImg:setVisible(false);

        if i <= totalGoodsCount and type(goodsList[i]) == "table" then
            grid:setVisible(true);

            local classId = goodsList[i]["class_id"];

            local count   = goodsList[i][3] or 0;

            -- 显示数量
            TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
            if count > 1 then
                -- 需要显示数量
                countLabel:setString(changeNumType(count));
            else
                countLabel:setVisible(false);
            end

            -- 显示商品图标
            local goodsIcon;
            local para;
            local ratioGet = getLocStr("probability_get_item");

            if type(classId) == "number" then
                goodsIcon = getItemIconPath(ItemM.query(classId, "icon"));

                local desc = PetM.query(PetM.getPetidByPieceid(classId), "desc");
                local itemName = ItemM.query(classId, "name")

                local detailStr = string.format(ratioGet, itemName);
                para = {["id"] = classId, ["desc"] = desc, ["detail"] = detailStr};

            elseif classId == "money" then
                goodsIcon = getLargeAttribIconPath("money");

                local itemName = FieldsM.query(classId, "name");
                local detailStr = string.format(ratioGet, itemName);
                para = {["detail"] = detailStr};
            else
                goodsIcon = getItemIconPath(goodsList[i]["icon"]);
                para = goodsList[i];
            end

            iconImg:loadTexture(goodsIcon);

            -- 注册点击事件
            self:clickShowDesc(grid, goodsList[i], para);
        else
            -- 剩余的格子,bg灰色显示
            iconImg:setVisible(false);
            setGrayTransMode(goodsBg, true);
        end
    end
end

-- 注册事件处理回调函数
function UISkyWhirlpoolInfo:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyWhirlpoolInfo");
            local uiForm = UIMgr.getCurrentScene():getFormByName("UISkyCity");
            if uiForm then
                uiForm:showInfoNode(true);
            end
        elseif eventType == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UISkyCity");
            if uiForm then
                uiForm:showInfoNode(false);
            end
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyWhirlpoolInfo", event.FOCUS_CHANGED, function(para)
        -- TODO
        if para["get"] == "UISkyWhirlpoolInfo" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_AIRSHIP_SCORE, TOPMENU_FRAME_AIRSHIP_ATTRIB, TOPMENU_FRAME_HEAD_AIRSHIP);
        elseif para["lose"] == "UISkyWhirlpoolInfo" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(false);
        end
    end);
end

-- 注册点击事件
function UISkyWhirlpoolInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyWhirlpoolInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 开始试炼按钮点击事件
    local btnFight = findChildByName(self.node, "BT/btn_make");
    local function onFightClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_click");
            -- 尝试开始试炼
            local uiSkyCity  = UIMgr.getCurrentScene():getFormByName("UISkyCity");
            uiSkyCity:doEvent();

            UIMgr.getCurrentScene():removeFormByName("UISkyWhirlpoolInfo");
        end
    end
    btnFight:addTouchEventListener(onFightClick);
    TextStyleM.setTextStyle(btnFight, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnFight:setTitleText(getLocStr("btn_text_attack"));
    btnFight:setVisible(true);
end

-- 设置信息的字体
function UISkyWhirlpoolInfo:setSystemTextStyle(textLabel)
    textLabel:setFontSize(TextStyleM.TEXT_SIZE_TINY);
    textLabel:setTextColor(TextStyleM.TEXT_COLOR_BRIGHT_BLUE);
    TextStyleM.setOutlineStyle(textLabel, 2, TextStyleM.TEXT_COLOR_DARK_BLUE2, true);
end

-- 根据当前抽取到的类型，重绘描述信息
function UISkyWhirlpoolInfo:redrawDesc()
    local descNode = findChildByName(self.node, "BT2/desc_node");
    local titleLabel = findChildByName(descNode, "title_label");
    local descLabel = findChildByName(descNode, "desc_label");

    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);

    local titleName = getLocStr("whirlpool_title");

    local color = CampM.query(self.camp, "whirlpool_color");
    local title = string.format(titleName, color);
    local descStr = string.format(getLocStr("whirlpool_desc"), color);

    titleLabel:setString(title);
    descLabel:setString(descStr);

    -- 对应的限制
    local kerning = -3;
    if not isFullWidthLang() then
        kerning = -1;
    end
    local subheadLabel = findChildByName(self.node, "BT2/desc_node/time_label");
    TextStyleM.setTextStyle(subheadLabel, TextStyleM.TEXT_SIZE_SMALL2,
    TextStyleM.TEXT_COLOR_GRAY, false, getLocKerning() + kerning);

    local titlePosX = titleLabel:getPositionX();
    local labelWidth = titleLabel:getContentSize().width;

    local timeLPosx = titlePosX + labelWidth + 20;
    subheadLabel:setPositionX(timeLPosx);
    subheadLabel:setVisible(true);

    local limitCamp = string.format(getLocStr("limit_camp"), CampM.query(self.camp, "name"));

    subheadLabel:setString(limitCamp);
end

-- 初始化奖励格子
function UISkyWhirlpoolInfo:initGrids(gridCount)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = -5;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 10;
    local bottomHGap  = 0;
    local leftWGap = 5;

    -- 总数
    local totalCount = gridCount;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/sky_city/SkyStoreItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留白
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    -- @param initHandle    格子初始化委托
    -- @param schedulerId   定时器id
    initScrollGridsVertical(self, self.scrollView, itemNode,
        totalCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap,
        iconWidth, iconHeight, topHGap, bottomHGap, leftWGap);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);
    end
end

-- 获得当前奖励的iconPath
function UISkyWhirlpoolInfo:getBonusIconPath(bonus)
    -- 默认为item图标
    local iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
    if bonus[1] == 1 then
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
    elseif bonus[1] == 2 then
        iconPath = getLargeAttribIconPath("gem_mid");
    elseif bonus[1] == 6 then
        iconPath = getAirShipSkillIconPath(SkyShipSkillM.query(bonus[2], "icon"));
    end

    return iconPath;
end

-- 点击图标处理
function UISkyWhirlpoolInfo:clickShowDesc(node, bonus, para)
    -- 点击处理
    local bg = findChildByName(node, "bg");
    bg:setTouchEnabled(true);
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("workshop_material");
            UIMgr:getCurrentScene():removeFormByName("UIItemDesc");
            if type(bonus["class_id"]) == "number" then
                -- 显示道具详细信息
                local uiItemDesc = UIItemDesc.create(bonus["class_id"], nil, para);

                UIMgr:getCurrentScene():addForm(uiItemDesc);
            elseif bonus["class_id"] == "money" then
                -- 显示信息
                local uiItemDesc = UIItemDesc.create(bonus["class_id"], nil, para);
                UIMgr:getCurrentScene():addForm(uiItemDesc);
            else
                -- 显示奖励描述信息
                local uiItemDesc = UIItemDesc.create(bonus["id"], nil, para);
                UIMgr:getCurrentScene():addForm(uiItemDesc);
            end
        end
    end);
end

-- 添加的塔只显示主塔
function UISkyWhirlpoolInfo:redrawTowerBg(towerNode)
    -- local towerNode = findChildByName(self.node, "CT/tower_node/tower");

    local allChildren = towerNode:getChildren();
    local len = table.getn(allChildren)

    if len < 0 then
        return;
    end

    for i = 1, len do
        local node = allChildren[i];
        local nodeName = node:getName();

        local iconList = {"devil", "flag", "flag_Copy", "weapon"};
        if string.startWith(nodeName, "tower_middle") or table.indexOf(iconList, nodeName) ~= -1
         or string.startWith(nodeName, "cloud_9") then
            node:setVisible(true);
        else
            node:setVisible(false);
        end
    end
end

-- 从中间浮现效果
function UISkyWhirlpoolInfo:comformCenterEffect()
    local BT2 = findChildByName(self.node, "BT2");
    local Top = findChildByName(self.node, "Top");
    if not BT2 or not Top then
        return;
    end

    local titleNode = findChildByName(Top, "title");
    local descNode = findChildByName(BT2, "desc_node");

    local oldScale = titleNode:getScale();
    local descSale = descNode:getScale();

    -- title
    titleNode:setScale(oldScale * 0.8);
    local scaleUp1 = cc.EaseIn:create(cc.ScaleTo:create(0.2, oldScale * 1.05), 0.4);
    local scaleUp2 = cc.ScaleTo:create(0.05, oldScale);
    titleNode:runAction(cc.Sequence:create(scaleUp1, scaleUp2));

    descNode:setScale(descSale * 0.8);
    local scaleUp3 = cc.EaseIn:create(cc.ScaleTo:create(0.2, descSale * 1.05), 0.4);
    local scaleUp4 = cc.ScaleTo:create(0.05, descSale);
    descNode:runAction(cc.Sequence:create(scaleUp3, scaleUp4));
end

-- 重置下value的位置
function UISkyWhirlpoolInfo:resetLabelPos(labelNode)
    local posX = labelNode:getPositionX();

    labelNode:setPositionX(posX + 20);
end

function UISkyWhirlpoolInfo:createWhirlpoolIsland(camp)
    local whirlpoolNode = cc.CSLoader:createNode("layout/sky_city/WhirlpoolItem.csb");

    local centerImg = findChildByName(whirlpoolNode, "center");
    local centerIcon = getWhirlpoolIcon("center_" .. camp);
    centerImg:loadTexture(centerIcon);
    for index = 1, 6 do
        local scrapNode = findChildByName(whirlpoolNode, "scrap_node" .. index);
        self:WhirlpoolScrapRotation(scrapNode);
    end

    return whirlpoolNode;
end

-- 转动动画
function UISkyWhirlpoolInfo:WhirlpoolScrapRotation(scrapNode)
    -- 先暂停下所有准心图片的行为
    scrapNode:stopAllActions();

    local delay = cc.DelayTime:create(0.1);
    local rotateRight = cc.RotateBy:create(5, 90);
    local rotateLeft = cc.RotateBy:create(5, -90);

    local action = cc.Sequence:create(rotateRight, delay, rotateLeft);

    scrapNode:runAction(cc.RepeatForever:create(action));
end